from typing import List, Optional
import logging
from tortoise.exceptions import DoesNotExist
from app.services.base_service import BaseService
from app.models.goods_models import Goods
from app.schemas.goods_schemas import GoodsCreate, GoodsUpdate

logger = logging.getLogger(__name__)

class GoodsService(BaseService):
    """商品服务类"""
    
    def __init__(self):
        super().__init__(Goods)
    
    @classmethod
    async def get_goods(cls, goods_id: int) -> Optional[Goods]:
        """根据ID获取商品"""
        logger = logging.getLogger(f"{__name__}.{cls.__name__}")
        try:
            logger.debug(f"获取商品信息: id={goods_id}")
            goods = await Goods.get_or_none(id=goods_id)
            if not goods:
                logger.warning(f"商品不存在: id={goods_id}")
            return goods
        except Exception as e:
            logger.error(f"获取商品信息失败: {str(e)}", exc_info=True)
            raise

    @classmethod
    async def create_goods(cls, goods_data: GoodsCreate) -> Goods:
        """创建新商品"""
        try:
            logger.info(f"开始创建商品: {goods_data.model_dump()}")
            
            # 如果没有提供商品编码，自动生成一个
            if not goods_data.code:
                goods_data.code = await cls.generate_unique_code()
                logger.info(f"自动生成商品编码: {goods_data.code}")
            else:
                # 检查商品编码是否已存在
                existing_goods = await Goods.get_or_none(code=goods_data.code)
                if existing_goods:
                    logger.warning(f"商品编码已存在: code={goods_data.code}")
                    raise ValueError(f"商品编码 '{goods_data.code}' 已存在")
            
            goods = await Goods.create(**goods_data.model_dump(exclude_unset=True))
            logger.info(f"商品创建成功: id={goods.id}")
            return goods
        
        except ValueError as e:
            logger.error(f"创建商品失败(数据验证): {str(e)}")
            raise
        except Exception as e:
            logger.error(f"创建商品失败: {str(e)}", exc_info=True)
            if "Duplicate entry" in str(e):
                raise ValueError(f"商品编码已存在")
            raise

    @classmethod
    async def list_goods(cls, skip: int = 0, limit: int = 10, category: Optional[str] = None) -> List[Goods]:
        """获取商品列表"""
        try:
            logger.info(f"获取商品列表: skip={skip}, limit={limit}, category={category}")
            query = Goods.all()
            if category:
                query = query.filter(category=category)
            goods_list = await query.offset(skip).limit(limit)
            logger.debug(f"成功获取商品列表: count={len(goods_list)}")
            return goods_list
        except Exception as e:
            logger.error(f"获取商品列表失败: {str(e)}", exc_info=True)
            raise

    @classmethod
    async def update_goods(cls, goods_id: int, goods_data: GoodsUpdate) -> Optional[Goods]:
        """更新商品信息"""
        try:
            goods = await cls.get_goods(goods_id)
            if goods:
                await goods.update_from_dict(goods_data.model_dump(exclude_unset=True))
                await goods.save()
                return goods
            return None
        except Exception as e:
            raise Exception(f"更新商品失败: {str(e)}")

    @classmethod
    async def delete_goods(cls, goods_id: int) -> bool:
        """删除商品"""
        try:
            goods = await cls.get_goods(goods_id)
            if goods:
                await goods.delete()
                return True
            return False
        except Exception as e:
            raise Exception(f"删除商品失败: {str(e)}")

    @classmethod
    async def generate_unique_code(cls, prefix: str = "GOODS") -> str:
        """生成唯一的商品编码"""
        import time
        import random
        
        while True:
            # 生成格式: PREFIX-TIMESTAMP-RANDOM
            timestamp = int(time.time() * 1000)
            random_num = random.randint(1000, 9999)
            code = f"{prefix}-{timestamp}-{random_num}"
            
            # 检查是否已存在
            existing = await Goods.get_or_none(code=code)
            if not existing:
                return code